import { createSlice } from "@reduxjs/toolkit";
import {
  getToken,
  getUserInfo,
  removeToken,
  removeUserInfo,
  setToken as _setToken,
  setUserInfo as _setUserInfo
} from "@/utils/index.jsx";
import { getProfileApi, loginApi } from "@/apis/user.jsx";

let userStore = createSlice({
  name: 'user',
  initialState: {
    token: getToken() || '',
    userInfo: getUserInfo() || {},
  },
  reducers: {
    /*
    * 设置token
    * */
    setToken: (state, action) => {
      state.token = action.payload;
      _setToken(action.payload)
    },
    /*
    * 设置用户学习
    * */
    setUserInfo: (state, action) => {
      state.userInfo = action.payload
      _setUserInfo(action.payload)
    },
    /*
    * 退出登入
    * */
    logout: (state) => {
      state.token = ''
      state.userInfo = {}
      removeToken()
      removeUserInfo()
    }
  }
});

const { setToken, setUserInfo, logout } = userStore.actions
// 获取reducer
const reducer = userStore.reducer

// ************异步方法***********

// 登入
const fetchLogin = (loginForm) => {
  return async (dispatch) => {
    const res = await loginApi(loginForm)
    dispatch(setToken(res.data.token))
  }
}

// 获取用户信息
const fetchGetUserInfo = () => {
  return async (dispatch) => {
    const res = await getProfileApi()
    dispatch(setUserInfo(res.data))
  }
}

export { setToken, logout, fetchLogin, fetchGetUserInfo }
export default reducer